package com.jessechanrui.template.common.template.auth.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.jessechanrui.template.common.template.auth.config.handler.CustomTenantLineHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author chenrui
 * @version 1.0
 * @description MyBatisPlusConfig
 * @date 2025/5/20
 */
@Configuration
public class MyBatisPlusConfig {
    // TODO: 暂且配置为默认的租户ID
    @Value("${auth.center.tenantId:tenant-agree}")
    private String tenantId;

    /**
     * 不需租户隔离的表
     */
    @Value("${tenant.ignoreTables:}")
    private List<String> ignoreTables;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件配置
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        // 指定数据库类型
        paginationInterceptor.setDbType(DbType.MYSQL);
        // 页码溢出处理（默认false，true表示页码超过最大页时返回最后一页数据）
        paginationInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(paginationInterceptor);
        //添加租户拦截器
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(tenantLineHandler()));
        return interceptor;
    }

    @Bean
    public TenantLineHandler tenantLineHandler() {
        return new CustomTenantLineHandler(ignoreTables, tenantId);
    }
}
